package nsu.grandfinal;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LocationPopup extends Activity {
	private LocationManager		myLocationManager;
	private String						provider;
	private double						latitude;
	private double						longitude;
	private Location					loc	= null;
	private Location					loc1;
	private float							distance;
	private LocationListener	myLocationListener;
	LinearLayout							LocationPopup;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.popup2);
		Intent intent = getIntent();
		latitude = intent.getDoubleExtra("Lat", 0);
		longitude = intent.getDoubleExtra("Lon", 0);
		String version = android.os.Build.VERSION.RELEASE;
		version = version.substring(0, 1);
		int v = Integer.parseInt(version);
		Log.i("version", version.substring(0, 1));
		if (v >= 3) new run().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
		else new run().execute("");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	private void getMyLocation() {
		myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		provider = myLocationManager.getBestProvider(new Criteria(), true);
		loc = myLocationManager.getLastKnownLocation(provider);
		loc1 = new Location(provider);
		loc1.setLatitude(latitude);
		loc1.setLongitude(longitude);
		myLocationListener = new LocationListener() {
			public void onStatusChanged(String provider, int status, Bundle extras) {
				distance = loc.distanceTo(loc1);
			}
			
			public void onProviderEnabled(String provider) {
				myLocationManager.requestLocationUpdates(provider, 0, 0, this);
			}
			
			public void onProviderDisabled(String provider) {}
			
			public void onLocationChanged(Location location) {
				loc = location;
			}
		};
	}
	
	protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
		super.onApplyThemeResource(theme, resid, first);
		theme.applyStyle(android.R.style.Theme_Panel, true);
	}
	
	private class run extends AsyncTask<String, Integer, Long> {
		@Override
		protected void onPreExecute() {
			LocationPopup = (LinearLayout) findViewById(R.id.LocationPopup);
			LocationPopup.setBackgroundColor(Color.rgb(125, 125, 125));
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
			TextView tv = (TextView) findViewById(R.id.txtSearch);
			tv.setText("위치검색중");
			super.onPreExecute();
		}
		
		@Override
		protected Long doInBackground(String... strData) {
			synchronized (this) {
				getMyLocation();
				int count = 0;
				while (true) {
					try {
						publishProgress();
						this.wait(1500);
						count++;
						Log.i("count", count + "");
						Log.i("cancled", isCancelled() + "");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if (loc.getAccuracy() <= 10) {
						break;
					}
					if (count > 5) {
						cancel(true);
						break;
					}
				}
				return null;
			}
		}
		
		@Override
		protected void onProgressUpdate(Integer... progress) {
			myLocationManager.requestLocationUpdates(provider, 0, 0, myLocationListener);
		}
		
		@Override
		protected void onPostExecute(Long result) {
			AlarmReceive ar = new AlarmReceive();
			distance = loc1.distanceTo(loc);
			ar.setDistance(distance);
			finish();
		}
		
		@Override
		protected void onCancelled() {
			AlertDialog.Builder cancle = new AlertDialog.Builder(LocationPopup.getContext());
			cancle.setMessage("위치검색에 실패하였습니다.\n 설정을 변경하겠습니까?").setCancelable(false).setPositiveButton("네", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					AlarmReceive ar = new AlarmReceive();
					ar.setDistance(10);
					finish();
				}
			}).setNegativeButton("아니요", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					AlarmReceive ar = new AlarmReceive();
					ar.setDistance(1);
					finish();
				}
			});
			AlertDialog alert = cancle.create();
			alert.setTitle("위치검색실패");
			alert.show();
			super.onCancelled();
		}
	}
}
